//
//  NibLoadable.swift
//  CooperSwift
//
//  Created by 计海峰 on 2021/5/19.
//

import UIKit

public protocol JHFNibLoadable {
    static var jhf_nibIdentifier: String { get }
}

extension JHFNibLoadable {
    static var jhf_nib: UINib {
        return UINib(nibName: jhf_nibIdentifier, bundle: nil)
    }
}

extension JHFNibLoadable where Self: UIView {
    public static func loadFromNib(_ bundle: Bundle? = nil) -> Self {
        guard let view = UINib(nibName: jhf_nibIdentifier, bundle: bundle).instantiate(withOwner: nil, options: nil).first as? Self else {
            fatalError("Couldn't find nib file for \(String(describing: Self.self))")
        }
        return view
        // return Bundle(for: Self.self).loadNibNamed("\(self)", owner: nil, options: nil)?.first as! Self
    }
}

extension JHFNibLoadable where Self: UIViewController {
    public static func loadFromNib(_ bundle: Bundle? = nil) -> Self {
        return Self(nibName: jhf_nibIdentifier, bundle: bundle)
    }
}

extension JHFNibLoadable where Self: UITableView {
    public static func loadFromNib(_ bundle: Bundle? = nil) -> Self {
        guard let tableView = UINib(nibName: jhf_nibIdentifier, bundle: bundle).instantiate(withOwner: nil, options: nil).first as? Self else {
            fatalError("Couldn't find nib file for \(String(describing: Self.self))")
        }
        return tableView
    }
}

extension JHFNibLoadable where Self: UITableViewController {
    public static func loadFromNib(_ bundle: Bundle? = nil) -> Self {
        return Self(nibName: jhf_nibIdentifier, bundle: bundle)
    }
}


// MARK:- 相应的类遵守协议
extension UIView: JHFNibLoadable {
    public static var jhf_nibIdentifier: String {
        return String(describing: self)
    }
}

extension UIViewController: JHFNibLoadable {
    public static var jhf_nibIdentifier: String {
        return String(describing: self)
    }
}
